package com.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.crm.base.ResponseResult;
import com.crm.domain.entity.Dept;
import com.crm.domain.entity.User;
import com.crm.domain.query.UserQuery;
import com.crm.domain.vo.UserVo;
import com.crm.mapper.UserMapper;
import com.crm.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Hulunico
 * @since 2024-08-08
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Override
    public Page<UserVo> queryAll(UserQuery userQuery) {
        //1.判断传过来的PageNum是否为空 为空就用默认值分页 不为空就用传过来的分页
        Page<User> page = ObjectUtil.isEmpty(userQuery.getPageNum()) ? Page.of(1, 10) : Page.of(userQuery.getPageNum(), userQuery.getPageSize());

        Map<String, Object> params = userQuery.getParams();

        if (params == null) {
            // 如果params为null，则给它赋一个空的HashMap
            params = new HashMap<>();
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate beginCreateTime = ObjectUtil.isEmpty(params.get("beginTime")) ? null : (LocalDate.parse( params.get("beginTime").toString(), formatter));
        LocalDate endCreateTime = ObjectUtil.isEmpty(params.get("endTime")) ? null : (LocalDate.parse( params.get("endTime").toString(), formatter));

        //分页查询条件
        LambdaQueryWrapper<User> wrapper= Wrappers.<User>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(userQuery.getUserName()),User::getUserName,userQuery.getUserName())
                .like(ObjectUtil.isNotEmpty(userQuery.getPhonenumber()),User::getPhonenumber,userQuery.getPhonenumber())
                .eq(ObjectUtil.isNotEmpty(userQuery.getDelFlag()),User::getDelFlag,userQuery.getDelFlag())
                .eq(ObjectUtil.isNotEmpty(userQuery.getDeptId()),User::getDeptId,userQuery.getDeptId())
                .between(ObjectUtil.isNotEmpty(beginCreateTime)&&ObjectUtil.isNotEmpty(endCreateTime),
                        User::getCreateTime,beginCreateTime,endCreateTime);
        Page<User> userPage= this.page(page, wrapper);
        /**
         * 分装部门信息
         */

        //如何把Page<User>转换成Page<UserVo>
        Page<UserVo> userVoPage = new Page();
        BeanUtil.copyProperties(userPage,userVoPage);

        List<UserVo> userVoList =new ArrayList<>();
        userPage.getRecords().forEach(user->{
            UserVo userVo = BeanUtil.copyProperties(user, UserVo.class);
            Dept dept = Db.lambdaQuery(Dept.class).eq(Dept::getDeptId, user.getDeptId()).one();
            userVo.setDept(dept);
            userVoList.add(userVo);
        });

        userVoPage.setRecords(userVoList);
        return userVoPage;

    }
private final UserMapper userMapper;
    @Override
    public ResponseResult getUserInfo() {
                return null;
    }



    @Override
    public void importData(MultipartFile file) throws IOException {
        List<User> list = getList(file);
        userMapper.batchInsert(list);

    }

    @Override
    public Map<String, Object> export() {
        //查询user所有数据
        List<User> userList = userMapper.selectList(Wrappers.emptyWrapper());
        String fileName = UUID.randomUUID().toString();

        if (ObjectUtil.isNotEmpty(userList)){
            Map<String, Object> map = new HashMap<>();
            //前端需要msg code
            map.put("msg", fileName);
            map.put("code", 200);
            return map;
        }
        return new HashMap<>();


    }

    private List<User> getList(MultipartFile file) throws IOException {
        //获取输入流并创建能读取Excel文件的工具
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());

        //把Excel文件的数据映射到user表里 并读取到List集合中
        List<User> userList = reader.readAll(User.class);

        //Wrappers.emptyWrapper()传入了一个空的查询条件，意味着查询所有用户
        List<User> userListDb = userMapper.selectList(Wrappers.emptyWrapper());

        // 假设基于用户名判断重复，根据实际情况选择属性
        boolean hasDuplicates = userList.stream()
                .map(User::getUserName)
                .anyMatch(userListDb.stream()
                        .map(User::getUserName)
                        .collect(Collectors.toSet())::contains);

        if (hasDuplicates) {
            throw new RuntimeException("存在重复数据");
        } else {
            System.out.println("没有重复数据");
        }
        return userList;
    }
}
